import React, { useState, useEffect } from 'react';
import { SearchBar, ActivityIndicator, ListView } from 'antd-mobile';
import ShowLoading from '@/components/ShowLoading';
import './index.less';
import useHttpHook from '@/hooks/useHttpHook';
import { history } from 'umi';
import { PAGE } from '@/enums/common';
export default function(props: any) {
  const { query }: any = props.location;

  const [houseName, setHouseName] = useState('');

  const [page, setPage] = useState({ pageSize: 8, pageNum: 1 });
  const [houseLists, setHouseLists]: any[] = useState([]);
  const [houseSubmitName, setHouseSubmitName] = useState('');

  const [house, loading]: any = useHttpHook({
    url: '/house/search',
    body: {
      ...page,
      houseName,
      code: query?.code,
      startTime: query?.startTime + ' 00:00:00',
      endTime: query?.endTime + ' 23:59:59',
    },
    watch: [page.pageNum, houseSubmitName],
  });
  const [showLoading, setShowLoading] = useState(true);

  useEffect(() => {
    if (!loading && house) {
      if (house.length) {
        setHouseLists([...houseLists, ...house]);
        if (house.length < page.pageSize) {
          setShowLoading(false);
        }
      } else {
        setShowLoading(false);
      }
    }
  }, [loading]);

  const handleEndReached = () => {
    if (!loading) {
      setPage({
        ...page,
        pageNum: page.pageNum + 1,
      });
    }
  };
  const handleChange = (value: string) => {
    setHouseName(value);
  };

  const handleSubmit = (value: string) => {
    setHouseName(value);
    setHouseSubmitName(value);
    setPage(PAGE);
    setHouseLists([]);
  };
  const handleCancel = () => {
    handleSubmit('');
  };
  const row = (item: any) => {
    return (
      <div
        className="item"
        key={item.id}
        onClick={() =>
          history.push({ pathname: '/house', query: { id: item.id } })
        }
      >
        <img src={item?.imgs[0]?.url} alt="" />
        <div className="item-right">
          <div className="title">{item.name}</div>
          <div className="price">{item.price}</div>
        </div>
      </div>
    );
  };
  const dataSource = new ListView.DataSource({
    rowHasChanged: (r1: any, r2: any) => r1 !== r2,
  });

  return (
    <div className="search-page">
      <SearchBar
        placeholder="搜索名宿"
        value={houseName}
        onChange={handleChange}
        onCancel={handleCancel}
        onSubmit={handleSubmit}
      />
      <div className="result">
        {loading ? (
          <ActivityIndicator toast />
        ) : (
          <ListView
            dataSource={dataSource.cloneWithRows(houseLists)}
            renderFooter={() => <ShowLoading showLoading={showLoading} />}
            style={{ height: '100vh' }}
            onEndReached={handleEndReached}
            renderRow={row}
            initialListSize={7}
          />
        )}
      </div>
    </div>
  );
}
